﻿using System;
using System.Activities.Statements;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web.Mvc;
using System.Text;
using System.EnterpriseServices;
using System.Configuration;
using Models;
using Common;
using Langben.DAL;
using Langben.BLL;
using Langben.App.Models;

namespace Langben.App.Controllers
{
     
    /// <summary>
    /// Cemetery
    /// </summary>
    public class CemeteryController : BaseController
    {

        SysEntities db=new SysEntities();
        /// <summary>
        /// 列表
        /// </summary>
        /// <returns></returns>
        [SupportFilter]
        public ActionResult DingJia()
        {
        
            return View();
        }

        public ActionResult Choose()
        {

            return View();
        }
         /// <summary>
        /// 列表
        /// </summary>
        /// <returns></returns>
        public ActionResult IndexSef()
        {

            return View();
        }
        /// <summary>
        /// 异步加载数据
        /// </summary>
        /// <param name="page">页码</param>
        /// <param name="rows">每页显示的行数</param>
        /// <param name="order">排序字段</param>
        /// <param name="sort">升序asc（默认）还是降序desc</param>
        /// <param name="search">查询条件</param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult GetData(string id, int page, int rows, string order, string sort, string search)
        {

            int total = 0;
            List<Cemetery> queryData = m_BLL.GetByParam(id, page, rows, order, sort, search, ref total);
            return Json(new datagrid
            {
                total = total,
                rows = queryData.Select(s => new
                {
                    RowGuid = s.RowGuid
					,QuGuid = s.QuGuid
					,Hao = s.Hao
					,Pai = s.Pai
                    ,
                    ShapeGuid = new ShapeBLL().GetById(s.ShapeGuid).Name
					,Price = s.Price
					,IsYanShou = s.IsYanShou
					
                }

                    )
            });
        }
        /// <summary>
        ///  导出Excle /*在6.0版本中 新增*/
        /// </summary>
        /// <param name="param">Flexigrid传过到后台的参数</param>
        /// <returns></returns>      
        [HttpPost]
        public ActionResult Export(string id, string title, string field, string sortName, string sortOrder, string search)
        {
            string[] titles = title.Split(',');//如果确定显示的名称，可以直接定义
            string[] fields = field.Split(',');
            List<Cemetery> queryData = m_BLL.GetByParam(id, sortOrder, sortName, search);
             
            return Content(WriteExcle(titles, fields, queryData.ToArray()));  
        }
        /// <summary>
        /// 查看详细
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [SupportFilter]  
        public ActionResult Details(string id)
        {
            Cemetery item = m_BLL.GetById(id);
            return View(item);

        }
 
        /// <summary>
        /// 首次创建
        /// </summary>
        /// <returns></returns>
        [SupportFilter]
        public ActionResult Create(string id)
        { 
            
            return View();
        }
         [SupportFilter]
        public ActionResult DanMuDingJia(string id)
        { 
            
            return View();
        }
        
        /// <summary>
        /// 创建
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        [SupportFilter]
        public ActionResult Create(Cemetery entity)
        {           
            if (entity != null && ModelState.IsValid)
            {
                string currentPerson = GetCurrentPerson();
                //entity.CreateTime = DateTime.Now;
                //entity.CreatePerson = currentPerson;
              
                entity.RowGuid = Result.GetNewId();   
                string returnValue = string.Empty;
                if (m_BLL.Create(ref validationErrors, entity))
                {
                    LogClassModels.WriteServiceLog(Suggestion.InsertSucceed  + "，Cemetery的信息的Id为" + entity.RowGuid,"Cemetery"
                        );//写入日志 
                    return Json(Suggestion.InsertSucceed);
                }
                else
                { 
                    if (validationErrors != null && validationErrors.Count > 0)
                    {
                        validationErrors.All(a =>
                        {
                            returnValue += a.ErrorMessage;
                            return true;
                        });
                    }
                    LogClassModels.WriteServiceLog(Suggestion.InsertFail + "，Cemetery的信息，" + returnValue,"Cemetery"
                        );//写入日志                      
                    return Json(Suggestion.InsertFail  + returnValue); //提示插入失败
                }
            }

            return Json(Suggestion.InsertFail + "，请核对输入的数据的格式"); //提示输入的数据的格式不对 
        }
        /// <summary>
        /// 首次编辑
        /// </summary>
        /// <param name="id">主键</param>
        /// <returns></returns> 
        [SupportFilter] 
        public ActionResult Edit(string id)
        {
            Cemetery item = m_BLL.GetById(id);
            return View(item);
        }
        /// <summary>
        /// 提交编辑信息
        /// </summary>
        /// <param name="id">主键</param>
        /// <param name="collection">客户端传回的集合</param>
        /// <returns></returns>
        [HttpPost]
        [SupportFilter]
        public ActionResult Edit(string id, Cemetery entity)
        {
            if (entity != null && ModelState.IsValid)
            {   //数据校验
            
                string currentPerson = GetCurrentPerson();                 
                //entity.UpdateTime = DateTime.Now;
                //entity.UpdatePerson = currentPerson;
                           
                string returnValue = string.Empty;   
                if (m_BLL.Edit(ref validationErrors, entity))
                {
                    LogClassModels.WriteServiceLog(Suggestion.UpdateSucceed + "，Cemetery信息的Id为" + id,"Cemetery"
                        );//写入日志                           
                    return Json(Suggestion.UpdateSucceed); //提示更新成功 
                }
                else
                { 
                    if (validationErrors != null && validationErrors.Count > 0)
                    {
                        validationErrors.All(a =>
                        {
                            returnValue += a.ErrorMessage;
                            return true;
                        });
                    }
                    LogClassModels.WriteServiceLog(Suggestion.UpdateFail + "，Cemetery信息的Id为" + id + "," + returnValue, "Cemetery"
                        );//写入日志                           
                    return Json(Suggestion.UpdateFail  + returnValue); //提示更新失败
                }
            }
            return Json(Suggestion.UpdateFail + "请核对输入的数据的格式"); //提示输入的数据的格式不对               
          
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="collection"></param>
        /// <returns></returns>   
        [HttpPost]
        public ActionResult Delete(FormCollection collection)
        {
            string returnValue = string.Empty;
            string[] deleteId = collection["query"].GetString().Split(',');
            if (deleteId != null && deleteId.Length > 0)
            { 
                if (m_BLL.DeleteCollection(ref validationErrors, deleteId))
                {
                    LogClassModels.WriteServiceLog(Suggestion.DeleteSucceed + "，信息的Id为" + string.Join(",", deleteId), "消息"
                        );//删除成功，写入日志
                    return Json("OK");
                }
                else
                {
                    if (validationErrors != null && validationErrors.Count > 0)
                    {
                        validationErrors.All(a =>
                        {
                            returnValue += a.ErrorMessage;
                            return true;
                        });
                    }
                    LogClassModels.WriteServiceLog(Suggestion.DeleteFail + "，信息的Id为" + string.Join(",", deleteId)+ "," + returnValue, "消息"
                        );//删除失败，写入日志
                }
            }
            return Json(returnValue);
        }
     
        IBLL.ICemeteryBLL m_BLL;

        ValidationErrors validationErrors = new ValidationErrors();
        public CemeteryController()
            : this(new CemeteryBLL()) { }
        public CemeteryController(CemeteryBLL bll)
        {
            m_BLL = bll;
        }
        /// <summary>
        /// 创建排号墓穴
        /// </summary>
        /// <param name="quguid"></param>
        /// <param name="painame"></param>
        /// <param name="paisort"></param>
        /// <param name="startno"></param>
        /// <param name="endno"></param>
        /// <param name="muxing"></param>
        /// <returns></returns>
        public JsonResult CreateCemetery(string quguid, string painame, int paisort, int startno, int endno, string muxing)
        {
            string currentPerson = GetCurrentPerson();
            string returnValue = string.Empty;
            List<Cemetery> cemeterylist=new List<Cemetery>();

            for (int i = startno; i <=endno; i++)
            {
                Cemetery cemetery = new Cemetery();
                cemetery.QuGuid = quguid;
                cemetery.RowGuid = Convert.ToString(Guid.NewGuid());
                cemetery.PaiName = painame;//排名称
                cemetery.Pai = paisort;//排排序
                cemetery.Hao = i;//一排的第几号
                cemetery.CreatePerson = currentPerson;
                cemetery.CreateTime = DateTime.Now;
                cemetery.ShapeGuid = muxing;//墓型
                cemeterylist.Add(cemetery);
            }
            CemeteryBLL bll=new CemeteryBLL();
            if (bll.CreateCollection(ref validationErrors, cemeterylist.AsQueryable()))
            {
                return Json("创建成功");
            }
            else
            {
                if (validationErrors != null && validationErrors.Count > 0)
                {
                    validationErrors.All(a =>
                    {
                        returnValue += a.ErrorMessage;
                        return true;
                    });
                }
            }



            return Json(returnValue);
        }
        /// <summary>
        /// 创建号
        /// </summary>
        /// <param name="quguid"></param>
        /// <param name="painame"></param>
        /// <param name="paisort"></param>
        /// <param name="startno"></param>
        /// <param name="endno"></param>
        /// <param name="muxing"></param>
        /// <returns></returns>
        public JsonResult CreateHao(string quguid, string haopainame, int haopaisort, int haostartno, int haoendno)
        {
            string currentPerson = GetCurrentPerson();
            string returnValue = string.Empty;
            List<Cemetery> cemeterylist = new List<Cemetery>();

            for (int i = haostartno; i <= haoendno; i++)
            {
                Cemetery cemetery = new Cemetery();
                cemetery.QuGuid = quguid;
                cemetery.RowGuid = Convert.ToString(Guid.NewGuid());
                cemetery.PaiName = haopainame;//排名称
                cemetery.Pai = haopaisort;//排排序
                cemetery.Hao = i;//一排的第几号
                cemetery.CreatePerson = currentPerson;
                cemetery.CreateTime = DateTime.Now;
                string muxing = string.Empty;
                try
                {
                    muxing = db.Cemetery.Where(s => s.Pai == haopaisort && s.QuGuid == quguid).Select(s => s.ShapeGuid).First();
                }
                catch (Exception)
                {
                    
                    throw;
                }
                cemetery.ShapeGuid = muxing;//墓型
                cemeterylist.Add(cemetery);
            }
            CemeteryBLL bll = new CemeteryBLL();
            if (bll.CreateCollection(ref validationErrors, cemeterylist.AsQueryable()))
            {
                return Json("创建成功");
            }
            else
            {
                if (validationErrors != null && validationErrors.Count > 0)
                {
                    validationErrors.All(a =>
                    {
                        returnValue += a.ErrorMessage;
                        return true;
                    });
                }
            }



            return Json(returnValue);
        }
        /// <summary>
        /// 获取墓地布局div
        /// </summary>
        /// <param name="quguid"></param>
        /// <returns></returns>
        public JsonResult GetCemeteryString(string quguid)
        {
            string currentPerson = GetCurrentPerson();
            string returnValue = string.Empty;
            StringBuilder sb = new StringBuilder();
 
            Area area=new Area();
            try
            {
                area = new SysEntities().Area.SingleOrDefault(s => s.Id == quguid);
            }
            catch (Exception)
            {
            
            }

            if (area != null)
            {
                string pai = area.Pai;
                string hao = area.Hao;
                IQueryable<int?> painolist;
                //从上往下
                if (string.IsNullOrEmpty(pai) || pai=="从上到下")
                {
                     painolist =
                    db.Cemetery.Where(s => s.QuGuid == quguid)
                        .GroupBy(l => l.Pai)
                        .OrderBy(p => p.Key)
                        .Select(g => g.Key);
                }
                else
                {
                    painolist =
                    db.Cemetery.Where(s => s.QuGuid == quguid)
                        .GroupBy(l => l.Pai)
                        .OrderByDescending(p => p.Key)
                        .Select(g => g.Key);
                }
                
                foreach (var paino in painolist)
                {
                    //根据paino获取painame
                    string paineme = string.Empty;
                    Cemetery painameCemetery = new Cemetery();
                    try
                    {
                        painameCemetery = db.Cemetery.First(s => s.Pai == paino && s.QuGuid == quguid);
                    }
                    catch (Exception)
                    {
                    }
                    if (painameCemetery != null)
                    {
                        paineme = painameCemetery.PaiName;
                    }

                    SetStart(sb);
                    CemeteryBLL cemeteryBll = new CemeteryBLL();
                    List<Cemetery> cemeterylist =new List<Cemetery>();
                    //从左到右
                    if (hao == "从左到右" || string.IsNullOrEmpty(hao))
                    {
                        cemeterylist = cemeteryBll.GetAll()
                            .Where(s => s.QuGuid == quguid && s.Pai == paino)
                            .OrderBy(p => p.Hao)
                            .ToList();
                    }
                    else
                    {
                        cemeterylist = cemeteryBll.GetAll()
                            .Where(s => s.QuGuid == quguid && s.Pai == paino)
                            .OrderByDescending(p => p.Hao)
                            .ToList();
                    }
                    
                    SetSelectAllPai(sb, paino, paineme);

                    foreach (var cemetery in cemeterylist)
                    {
                        SetCemeteryEntity(sb, cemetery);
                    }

                    SetEnd(sb);
                }
            }
            returnValue = Convert.ToString(sb);

            return Json(returnValue);
        }
        /// <summary>
        /// 设置节点
        /// </summary>
        /// <param name="sb"></param>
        /// <param name="cemetery"></param>
        private void SetCemeteryEntity(StringBuilder sb, Cemetery cemetery)
        {
            sb.Append("<li>");
            sb.Append("<img src='../../Images/danmu.gif' />");
            sb.Append("<br />");
            sb.Append(cemetery.Hao);
            sb.Append("<br />");
            sb.Append("<input type='checkbox' name='cemetery" + cemetery.Pai + "' value='" + cemetery.RowGuid +
                      "' /></li>");
        }
        private void SetSelectAllPai(StringBuilder sb,int? paino,string painame)
        {
            sb.Append("<li>" + painame + "：<br /><input type='checkbox' name='cemetery" + paino + "' id='cemetery" + paino + "' /></li>");
        }
        /// <summary>
        /// 设置div结尾
        /// </summary>
        /// <param name="sb"></param>
        private void SetEnd(StringBuilder sb)
        {
            sb.Append("</ul>");
        }
        /// <summary>
        /// 设置div的开头
        /// </summary>
        /// <param name="sb"></param>
        private void SetStart(StringBuilder sb)
        {
            sb.Append("<ul>");
        }
        public JsonResult GetPai(string quguid)
        {

            var pai = new SysEntities().Cemetery.Where(s => s.QuGuid == quguid).GroupBy(g => new {g.Pai, g.PaiName}).Select(p=>p.Key);

            return Json(pai);

        }
        public JsonResult EditPai(FormCollection collection, string painame,int paisort,string quguid)
        {
            string returnValue = string.Empty;
            string[] editId = collection["query"].GetString().Split(',');
            if (editId != null && editId.Length > 0)
            {
                List<Cemetery> cemeteries=new List<Cemetery>();
                CemeteryBLL cemeteryBll=new CemeteryBLL();
                foreach (var editid in editId)
                {
                    if (!string.IsNullOrEmpty(editid))
                    {
                        Cemetery cemetery =  db.Cemetery.SingleOrDefault(s => s.RowGuid == editid);
                        cemetery.PaiName = painame;
                        cemetery.Pai = paisort;
                        string muxing = string.Empty;
                        try
                        {
                            muxing = db.Cemetery.Where(s => s.Pai == paisort && s.QuGuid == quguid).Select(s => s.ShapeGuid).First();
                        }
                        catch (Exception)
                        {

                            throw;
                        }
                        cemetery.ShapeGuid = muxing;//墓型
                        db.Detach(cemetery);
                        cemeteries.Add(cemetery);
                       
                    }
                }
                if (m_BLL.EditCollection(ref validationErrors, cemeteries.AsQueryable()))
                {
                    LogClassModels.WriteServiceLog(Suggestion.UpdateSucceed + "，信息的Id为" + string.Join(",", editId), "消息"
                        );//删除成功，写入日志
                    return Json("OK");
                }
                else
                {
                    if (validationErrors != null && validationErrors.Count > 0)
                    {
                        validationErrors.All(a =>
                        { 
                            returnValue += a.ErrorMessage;
                            return true;
                        });
                    }
                    LogClassModels.WriteServiceLog(Suggestion.UpdateFail + "，信息的Id为" + string.Join(",", editId) + "," + returnValue, "消息"
                        );//删除失败，写入日志
                }
            }
            return Json(returnValue);
        }
        public JsonResult EditHao(FormCollection collection, int edithao )
        {
            string returnValue = string.Empty;
            string[] editId = collection["query"].GetString().Split(',');
            if (editId != null && editId.Length > 0)
            {
                List<Cemetery> cemeteries = new List<Cemetery>();
                
                foreach (var editid in editId)
                {
                    if (!string.IsNullOrEmpty(editid))
                    {
                        Cemetery cemetery = db.Cemetery.SingleOrDefault(s => s.RowGuid == editid);
                        cemetery.Hao = edithao;
                         
                        db.Detach(cemetery);
                        cemeteries.Add(cemetery);

                    }
                }
                if (m_BLL.EditCollection(ref validationErrors, cemeteries.AsQueryable()))
                {
                    LogClassModels.WriteServiceLog(Suggestion.UpdateSucceed + "，信息的Id为" + string.Join(",", editId), "消息"
                        );//删除成功，写入日志
                    return Json("OK");
                }
                else
                {
                    if (validationErrors != null && validationErrors.Count > 0)
                    {
                        validationErrors.All(a =>
                        {
                            returnValue += a.ErrorMessage;
                            return true;
                        });
                    }
                    LogClassModels.WriteServiceLog(Suggestion.UpdateFail + "，信息的Id为" + string.Join(",", editId) + "," + returnValue, "消息"
                        );//删除失败，写入日志
                }
            }
            return Json(returnValue);
        }
        public JsonResult YanShou(FormCollection collection, string yanshou)
        {
            string returnValue = string.Empty;
            string[] editId = collection["query"].GetString().Split(',');
            if (editId != null && editId.Length > 0)
            {
                List<Cemetery> cemeteries = new List<Cemetery>();

                foreach (var editid in editId)
                {
                    if (!string.IsNullOrEmpty(editid))
                    {
                        Cemetery cemetery = db.Cemetery.SingleOrDefault(s => s.RowGuid == editid);
                        cemetery.IsYanShou = yanshou;

                        db.Detach(cemetery);
                        cemeteries.Add(cemetery);

                    }
                }
                if (m_BLL.EditCollection(ref validationErrors, cemeteries.AsQueryable()))
                {
                    LogClassModels.WriteServiceLog(Suggestion.UpdateSucceed + "，信息的Id为" + string.Join(",", editId), "消息"
                        );//删除成功，写入日志
                    return Json("OK");
                }
                else
                {
                    if (validationErrors != null && validationErrors.Count > 0)
                    {
                        validationErrors.All(a =>
                        {
                            returnValue += a.ErrorMessage;
                            return true;
                        });
                    }
                    LogClassModels.WriteServiceLog(Suggestion.UpdateFail + "，信息的Id为" + string.Join(",", editId) + "," + returnValue, "消息"
                        );//删除失败，写入日志
                }
            }
            return Json(returnValue);
        }

        public JsonResult AreaDingJia(string quguid, decimal price)
        {
            string returnValue = string.Empty;
            List<Cemetery> cemeteries = db.Cemetery.Where(s => s.QuGuid == quguid).ToList();
            
            foreach (var cemetery in cemeteries)
            {
                cemetery.Price = price;
                db.Detach(cemetery);
            }
            if (m_BLL.EditCollection(ref validationErrors, cemeteries.AsQueryable()))
            {
                LogClassModels.WriteServiceLog(Suggestion.UpdateSucceed + "，区域的Id为" + string.Join(",", quguid), "消息"
                    ); //删除成功，写入日志
                return Json("OK");
            }
            else
            {
                if (validationErrors != null && validationErrors.Count > 0)
                {
                    validationErrors.All(a =>
                    {
                        returnValue += a.ErrorMessage;
                        return true;
                    });
                }
                LogClassModels.WriteServiceLog(
                    Suggestion.UpdateFail + "，区域的Id为" + string.Join(",", quguid) + "," + returnValue, "消息"
                    ); //删除失败，写入日志
            }

            return Json(returnValue);
        }

        public JsonResult MuXingDingJia(string quguid, decimal price,string muxing)
        {
            string returnValue = string.Empty;
            List<Cemetery> cemeteries = db.Cemetery.Where(s => s.QuGuid == quguid && s.ShapeGuid == muxing).ToList();
            
            foreach (var cemetery in cemeteries)
            {
                cemetery.Price = price;
                db.Detach(cemetery);
            }
            if (m_BLL.EditCollection(ref validationErrors, cemeteries.AsQueryable()))
            {
                LogClassModels.WriteServiceLog(Suggestion.UpdateSucceed + "，区域的Id为" + string.Join(",", quguid), "消息"
                    ); //删除成功，写入日志
                return Json("OK");
            }
            else
            {
                if (validationErrors != null && validationErrors.Count > 0)
                {
                    validationErrors.All(a =>
                    {
                        returnValue += a.ErrorMessage;
                        return true;
                    });
                }
                LogClassModels.WriteServiceLog(
                    Suggestion.UpdateFail + "，区域的Id为" + string.Join(",", quguid) + "," + returnValue, "消息"
                    ); //删除失败，写入日志
            }

            return Json(returnValue);
        }

        public JsonResult AjaxDingJia(FormCollection collection, decimal price)
        {
            string returnValue = string.Empty;
            string[] editId = collection["query"].GetString().Split(',');
            if (editId != null && editId.Length > 0)
            {
                List<Cemetery> cemeteries = new List<Cemetery>();

                foreach (var editid in editId)
                {
                    if (!string.IsNullOrEmpty(editid))
                    {
                        Cemetery cemetery = db.Cemetery.SingleOrDefault(s => s.RowGuid == editid);
                        cemetery.Price = price;

                        db.Detach(cemetery);
                        cemeteries.Add(cemetery);

                    }
                }
                if (m_BLL.EditCollection(ref validationErrors, cemeteries.AsQueryable()))
                {
                    LogClassModels.WriteServiceLog(Suggestion.UpdateSucceed + "，信息的Id为" + string.Join(",", editId), "消息"
                        );//删除成功，写入日志
                    return Json("OK");
                }
                else
                {
                    if (validationErrors != null && validationErrors.Count > 0)
                    {
                        validationErrors.All(a =>
                        {
                            returnValue += a.ErrorMessage;
                            return true;
                        });
                    }
                    LogClassModels.WriteServiceLog(Suggestion.UpdateFail + "，信息的Id为" + string.Join(",", editId) + "," + returnValue, "消息"
                        );//删除失败，写入日志
                }
            }
            return Json(returnValue);
        }

        public string GetFullName(string rowguid)
        {
            string ret = string.Empty;
            Cemetery cemetery=new Cemetery();

            cemetery = new CemeteryBLL().GetById(rowguid);
            Area qu = new SysEntities().Area.SingleOrDefault(s => s.Id == cemetery.QuGuid);
            Area pian = new SysEntities().Area.SingleOrDefault(s => s.Id == qu.ParentId);
            Area yuan = new SysEntities().Area.SingleOrDefault(s => s.Id == pian.ParentId);
            ret = yuan.MyTexts + pian.MyTexts + qu.MyTexts + "第" + cemetery.Pai + "排" + "第" + cemetery.Hao + "号";
            return ret;
        }
        
    }
}


